package com.siki.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.imageseg.model.v20191230.SegmentBodyRequest;
import com.aliyuncs.imageseg.model.v20191230.SegmentBodyResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.siki.Utils.OSSUtils;
import com.siki.Utils.SystemMsgJsonResponse;
import com.siki.Utils.fileUtils.FileUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import static com.siki.Utils.AccessKeyIdUtils.*;

@RestController
@RequestMapping("/photo")
@CrossOrigin
public class PhotoController {

    @ApiOperation(value = "图片切割",consumes = "application")
    @RequestMapping(value = "/photo_cut",method = RequestMethod.POST)
    public SystemMsgJsonResponse photo_cut(@RequestParam MultipartFile file) throws InterruptedException, IOException, ClientException {
        String new_file_path = FileUtils.upload_file(file);
        //休眠
        Thread.sleep(1000);
        String file_oss_url = OSSUtils.file_get_oss_url(new_file_path);
        JSONObject cut_photo = get_cut_photo(file_oss_url);

        JSONObject data = new JSONObject();
        data.put("imageURL",cut_photo.get("data"));
        data.put("requestId",cut_photo.get("requestId"));
        return SystemMsgJsonResponse.success(data);
    }

        public static JSONObject get_cut_photo(String photo_url) throws ClientException {
            DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai",
                    ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            IAcsClient client = new DefaultAcsClient(profile);
            SegmentBodyRequest request = new SegmentBodyRequest();
            request.setRegionId("cn-shanghai");
            request.setImageURL(photo_url);
            SegmentBodyResponse response = client.getAcsResponse(request);
            return JSONObject.parseObject(new Gson().toJson(response));
        }
}
